<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Announcement extends Model
{
    protected $fillable = [
        'title', 'content', 'status', 'poster_id', 'poster_name', 'company_id', 'site_id'
    ];
    
    public function company() {
        return $this->hasOne('\App\Models\Company', 'Co_ID', 'company_id');
    }
    
    public function site() {
        return $this->hasOne('\App\Models\Site', 'id', 'site_id');
    }
    
    protected $casts = [
        'company_id'=>'integer',
        'site_id'=>'integer',
    ];
    
    //获取最新已发布公告
    public function getLastAnnounce($user) {
        if($user->isSuperAdmin()){
            return null;
        }
        $cid = $user->Co_ID;
        $sid = $user->scope;
        return $this
                ->select(['title', 'content', 'poster_name', 'created_at'])
                ->where('company_id', $cid)
                ->where('site_id', $sid)
                ->where('status', 1)
                ->first();
    }
    
    public function getAllAnnounce($user) {
        if($user->isSuperAdmin()){
            return [];
        }
        return $this
                ->select(['id', 'title'])
                ->where('status', 1)
                ->limit(5)
                ->orderBy('updated_at', 'desc')
                ->get();
    }
}
